import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Card, Table, Select, DatePicker, Radio, Row  } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { formLayout } from '@/utils/utils'
import RenderButtom from '@/components/RenderButton'
import { fetchReportList, fetchFinaRpt, exportExcel } from '@/services/dataCenter/financeData'
import SearchBox from '@/components/SearchBox'
const {RangePicker} = DatePicker
import moment from 'moment'

const FinancialReports = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [reportList, setReportList] = useState([])
  const [total, setTotalPage] = useState(null)
  const [dateFormat, setDateFormat] = useState('YYYY-MM-DD')
  const [pageInfo, setPageInfo] = useState({ pageTurnoverTotalMoney: 0, pageRefundMoney: 0})
  const [totalInfo, setTotalInfo] = useState({turnoverTotalMoney: 0, refundTotalMoney: 0})

  const [reqForm, setReqForm] = useState({
    orderStartTime: moment().format('YYYY-MM-DD'),
    orderEndTime: moment().format('YYYY-MM-DD'),
    queryType: '',
    supplierId: '',
    storeId: '',
  })

  const param = {
    pageSize: 10,
    pageNo: 1,
    startTime: moment().format('YYYY-MM-DD'),
    endTime: moment().format('YYYY-MM-DD'),
    queryType: 'day'
  }

  useEffect(() => {
    init()
  }, [])
  const init = async (param) => {
    console.log(param)
    const r_1 = await fetchReportList(param)
    if (r_1.code == 0 && r_1.data) {
      setReportList(r_1.data)
      setTotalPage(r_1.total)
      setPageInfo({
        pageTurnoverTotalMoney: r_1.pageTurnoverTotalMoney,
        pageRefundMoney: r_1.pageRefundMoney,
      })
    }
    const r_2 = await fetchFinaRpt(param)
    if (r_2.code == 0 && r_2.data) {
      setTotalInfo(r_2.data)
    }
  }
  const pagination = {
    total: parseInt(total),
    onChange (page) {
      init({
        ...param,
        pageNo: page,
      })
    }
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }

  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log(dateFormat)
      init({
        ...values,
        startTime: values.selectedTime[0].format(dateFormat),
        endTime: dateFormat == 'quarter' ? 'null' : values.selectedTime[1].format(dateFormat),
      })
    })
  }

  const storeTypes = [{
    value: 1,
    label: '机构结算'
  },{
    value: 2,
    label: '平台结算'
  }]
  const handleChangeType =(e) => {
    let val = e.target.value
    switch (val) {
      case 'day':
        setDateFormat('YYYY-MM-DD')
        break;
      case 'month':
        setDateFormat('YYYY-MM')
        break;
      case 'quarter':
        setDateFormat('YYYY')
        break;
      case 'year':
        setDateFormat('YYYY')
        break;
      default:
        break;
    }
  }

  // 查询条件
  const getFields = () => {
    return(<>
      <Col span={8}>
        <Form.Item label="门店" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
          {getFieldDecorator('storeId', {
            initialValue: '2063',
          })
            (<Select></Select>)}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="结算类型" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
          {getFieldDecorator('storeType', {})
            (<Select>
              {storeTypes.map((m, i) => <Select.Option key={i} value={m.value}>{m.label}</Select.Option>)}
            </Select>)}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label={`筛选时间`} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
          {getFieldDecorator(`selectedTime`, {
            initialValue: [moment(), moment()],
            // defaultValue: [moment(), moment()],
          })
            (<RangePicker format={dateFormat} />)}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label={`日期阶段`} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
          {getFieldDecorator(`queryType`, {initialValue: 'day'})
            (<Radio.Group buttonStyle="solid" onChange={handleChangeType}>
              <Radio.Button value="day">日</Radio.Button>
              <Radio.Button value="month">月</Radio.Button>
              <Radio.Button value="quarter">季度</Radio.Button>
              <Radio.Button value="year">年</Radio.Button>
            </Radio.Group>)}
        </Form.Item>
      </Col>
    </>)
  }

  const reportColumns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (v, r, i) => {
        return (<span>{i+1}</span>)
      }
    },
    {
      title: '时间',
      dataIndex: 'queryDate',
      key: 'queryDate',
    },
    {
      title: '门店名称',
      dataIndex: 'storeName',
      key: 'storeName',
    },
    {
      title: '总销量',
      dataIndex: 'totalSales',
      key: 'totalSales'
    },
    {
      title: '总销售额',
      dataIndex: 'totalMoney',
      key: 'totalMoney'
    },
    {
      title: '总退款量',
      dataIndex: 'refundCount',
      key: 'refundCount',
    },
    {
      title: '总退款额',
      dataIndex: 'refundMoney',
      key: 'refundMoney',
      render: (v, r, i) => {
        return (<span>￥ {v}</span>  )
      }
    },
    {
      title: '微信',
      dataIndex: 'wxpMoney',
      key: 'wxpMoney',
      render: (v, r, i) => {
        return (<span>￥ {v}</span>  )
      }
    },
    {
      title: '支付宝',
      dataIndex: 'alpMoney',
      key: 'alpMoney',
      render: (v, r, i) => {
        return (<span>￥ {v}</span>  )
      }
    },
    {
      title: '银行卡',
      dataIndex: 'bankMoney',
      key: 'bankMoney',
      render: (v, r, i) => {
        return (<span>￥ {v}</span>  )
      }
    },
    {
      title: '其他',
      dataIndex: 'otherMoney',
      key: 'otherMoney',
      render: (v, r, i) => {
        return (<span>￥ {v}</span>  )
      }
    },
  ]
  // 按钮处理
  const handleBtn = type => {
    switch (type) {
      case 97:
        form.validateFields(async (err, values) => {
          console.log(values)
          exportExcel(values).then(() => {
            console.log(res)
          })
        })
        break;
      default:
        break;
    }
  }
  return (<PageHeaderWrapper>
    <Card>
      <Form layout={formLayout}>
        <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      </Form>
    </Card>
    <Card style={{marginTop: '10px'}}>
      <RenderButtom click={handleBtn} />
      <Table rowKey={record => record.id} pagination={pagination} size="small" columns={reportColumns} dataSource={reportList}/>
      <p>总 计：总交易：¥{totalInfo.turnoverTotalMoney} 总退款：¥{totalInfo.refundTotalMoney}</p>
      <p>页小计：总交易：¥{pageInfo.pageTurnoverTotalMoney} 退款: ¥{pageInfo.pageRefundMoney}</p>
    </Card>
  </PageHeaderWrapper>)
}

export default Form.create()(FinancialReports)
